//
//  CHBOAuthViewController.swift
//  weibo.chb
//
//  Created by 褚红彪 on 16/2/6.
//  Copyright © 2016年 chuhongbiao. All rights reserved.
//
import UIKit
import SVProgressHUD
let  CLIENT_ID = "642167127"
let  APP_SECRET = "84d94c0cca7b72cd39168b12da706d91"
let  REDIRECT_URI = "https://www.baidu.com/"
class CHBOAuthViewController: UIViewController,UIWebViewDelegate {
    private lazy var CHBWebView = UIWebView()
    override func loadView() {
        view = CHBWebView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(CLIENT_ID)&redirect_uri=\(REDIRECT_URI)"
        let url = NSURL(string: urlStr)!
        CHBWebView.loadRequest(NSURLRequest(URL: url))
        CHBWebView.delegate = self
        setUpUI()
    }
    func setUpUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "fillAuto")
        navigationItem.title = "微博登陆"
    }
    @objc private func cancel()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fillAuto()
    {
        print("自动填充")
        //用于填充js页面的字符串
        let jsString = "document.getElementById('userId').value='869922457@qq.com';document.getElementById('passwd').value='19890427'"
        //将该字符串转变为js所用的字符串填充到页面上(账号和密码)
        CHBWebView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    func loadAccesstoken(code: String){
        let params = [
            "client_id":CLIENT_ID,
            "client_secret":APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
        ]
        CHBNetworkTools.shareTools.request(.POST, urlString: "https://api.weibo.com/oauth2/access_token", params: params) { (response, error) -> () in
            if error != nil{
                print("返回错误:\(error)")
                return
            }
            guard let dict = response as? [String : AnyObject] else{
                print("response不是字典")
                return
            }
            let userAccount = CHBUserAccountModel(dict: dict)
            print("userAccount:\(userAccount)")
            print(response)
        }
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
        //设置一个闭包，确保网络请求的存在
        guard let url = request.URL?.absoluteString else{
            return true
        }
        //如果这个网络请求的地址不是以我们自己设置的回调页开头则直接返回
        if(!url.hasPrefix(REDIRECT_URI)){
            return true
        }
        print(request.URL?.query)
        //如果是以回调页开头则截取code（授权码）的内容
        let code = request.URL?.query?.substringFromIndex("code=".endIndex)
        print(code)
        loadAccesstoken(code!)
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
